<!-- 盘点单新增界面 -->
<template>
    <!--基本信息-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">基础信息</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-form :model="checkform" :rules="rules" ref="checkref" style="margin-top: 20px;margin-left: 50px;" label-width="auto">
            <el-row>
                <el-col :span="11">
                    <el-form-item label="盘点单号" prop="code">
                        <el-input placeholder="自动获取编号" style="width: 300px;" v-model="checkform.code" disabled></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="盘点类型" prop="type">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="checkform.type">
                            <el-option v-for="item in types" :key="item.bus_id" :label="item.bus_name" :value="item.bus_name"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="盘点开始时间" prop="start_time">
                        <el-date-picker
                            v-model="checkform.start_time"
                            type="datetime"
                            placeholder="请选择"
                            format="YYYY-MM-DD HH:mm:ss"
                            date-format="MMM DD, YYYY"
                            time-format="HH:mm"
                            style="width: 300px;"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="盘点结束时间" prop="end_time">
                        <el-date-picker
                            v-model="checkform.end_time"
                            type="datetime"
                            placeholder="请选择"
                            format="YYYY-MM-DD HH:mm:ss"
                            date-format="MMM DD, YYYY"
                            time-format="HH:mm"
                            style="width: 300px;"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="11">
                    <el-form-item label="仓库名称" prop="whid">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="checkform.whid" @change="warehouseChange">
                            <el-option v-for="item in warehouse" :key="item.wh_id" :label="item.wh_name" :value="item.wh_id"></el-option>
                        </el-select>
                        <el-button type="success" text="设置" @click="SetWarehouse">设置</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="11">
                    <el-form-item label="经办人" prop="user">
                        <el-select placeholder="请选择" style="width: 300px;" v-model="checkform.user" @change="handleUserChange">
                            <el-option v-for="item in users" :key="item.user_id" :label="item.user_name" :value="item.user_id"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="20">
                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" placeholder="请输入" v-model="checkform.remark"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>


     <!--盘点明细-->
     <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">盘点明细</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <div style="text-align: left;margin-left: 20px;">
            <el-button type="success" @click="ShowProduct">添加</el-button>
            <el-button @click="batchRemoveProducts">移除</el-button>
        </div>
        <!--表格-->
        <el-table :data="selectedProducts" stripe style="margin-top: 10px;" @selection-change="SelectChange">
            <el-table-column type="selection" fixed></el-table-column>
            <el-table-column type="index" fixed label="序号" width="70"></el-table-column>
            <el-table-column prop="proc_name" fixed label="货品名称" width="200"></el-table-column>
            <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
            <el-table-column prop="proc_model" label="规格型号" width="200"></el-table-column>
            <el-table-column prop="proc_primary_unit" label="单位" width="70"></el-table-column>
            <el-table-column prop="type_name" label="货品类型" width="200"></el-table-column>
            <el-table-column prop="stk_hand_num" label="账面数量" width="150">
                <template #default="scope">
                    {{ scope.row.stk_hand_num || 0 }}
                </template>
            </el-table-column>
            <el-table-column prop="stk_total" label="账面金额" width="150">
                <template #default="scope">
                    {{ scope.row.stk_total ? Number(scope.row.stk_total).toFixed(2) : '0.00' }}
                </template>
            </el-table-column>
            <el-table-column prop="check_num" label="实盘数量" width="200">
                <template #default="scope">
                    <el-input-number v-model="scope.row.check_num" :min="0" @change="calculateDifference(scope.row)" style="width: 150px;"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="price" label="参考单价" width="200">
                <template #default="scope">
                    <el-input-number 
                        v-model="scope.row.price" 
                        :min="0" 
                        :precision="2" 
                        @change="calculateDifference(scope.row)" 
                        style="width: 150px;"
                    ></el-input-number>
                </template>
            </el-table-column>
            <el-table-column prop="profit_loss_num" label="盈亏数量" width="150">
                <template #default="scope">
                    <span :style="{ color: scope.row.profit_loss_num > 0 ? '#67C23A' : (scope.row.profit_loss_num < 0 ? '#F56C6C' : 'inherit') }">
                        {{ scope.row.profit_loss_num || 0 }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="profit_loss_amount" label="盈亏金额" width="150">
                <template #default="scope">
                    <span :style="{ color: scope.row.profit_loss_amount > 0 ? '#67C23A' : (scope.row.profit_loss_amount < 0 ? '#F56C6C' : 'inherit') }">
                        {{ scope.row.profit_loss_amount ? Number(scope.row.profit_loss_amount).toFixed(2) : '0.00' }}
                    </span>
                </template>
            </el-table-column>
            <el-table-column prop="check_status" label="盘点状态" width="150">
                <template #default="scope">
                    <el-tag 
                        :type="scope.row.profit_loss_num > 0 ? 'success' : (scope.row.profit_loss_num < 0 ? 'danger' : 'info')"
                        effect="plain"
                    >
                        {{ scope.row.profit_loss_num > 0 ? '盘盈' : (scope.row.profit_loss_num < 0 ? '盘亏' : '无盈亏') }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="150">
                <template #default="scope">
                    <el-input v-model="scope.row.remark" placeholder="备注" style="width: 120px;"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right">
                <template #default="scope">
                    <el-button type="danger" size="small" text="移除" @click="removeProduct(scope.row.proc_id)">移除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 汇总信息 -->
        <div style="display: flex; justify-content: flex-end; margin-top: 15px; padding-right: 20px;">
            <div style="text-align: right;">
                <span style="margin-right: 20px;">货品种类: <b style="color: #409EFF;">{{ selectedProducts.length }}</b></span>
                <span style="margin-right: 20px;">盘点总数量: <b style="color: #409EFF;">{{ calculateTotalQuantity() }}</b></span>
                <span style="margin-right: 20px;">盘盈数量: <b style="color: #67C23A;">{{ calculateProfitQuantity() }}</b></span>
                <span style="margin-right: 20px;">盘亏数量: <b style="color: #F56C6C;">{{ calculateLossQuantity() }}</b></span>
                <span style="margin-right: 20px;">盘盈金额: <b style="color: #67C23A;">{{ calculateProfitAmount() }}</b></span>
                <span>盘亏金额: <b style="color: #F56C6C;">{{ calculateLossAmount() }}</b></span>
            </div>
        </div>
    </div>



    <!--上传附件-->
    <div class="white-container">
        <h3 style="text-align: left;margin-left: 20px;padding-top: 20px;">上传附件</h3>
        <hr style="border:1px solid #ccd0d4;"/>
        <el-upload
            :file-list="filelist" 
            class="upload-demo"
            action="http://localhost:5194/api/PublicFile/Uploadfile"
            multiple
            name="files"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="3"
            :on-exceed="handleExceed"
            :on-success="handleFileSuccess"
            :headers="headers"
            style="text-align: left;margin-left: 20px;">
            <el-button type="primary">上传附件</el-button>
                <template #tip>
                    <div class="el-upload__tip">
                        您可以上传doc, pdf, rar等格式的文件，单个文件上传最大200MB。
                    </div>
                </template>
        </el-upload>
    </div>


    <!-- 底部操作栏 -->
    <div class="action-bar">
        <el-button @click="Close">关闭</el-button>
        <el-button @click="SaveAsDraft">保存为草稿</el-button>
        <el-button @click="OKAdd">保存并新增</el-button>
        <el-button type="primary" @click="OK">保存</el-button>
    </div>


    <!--展示货品信息模态框-->
    <el-dialog v-model="dialogTableVisible" title="添加货品" width="800" close-on-click-modal="false">
        <div>
            <el-form :model="procform" ref="procref" :inline="true" style="text-align: left;">
                <el-form-item label="货品名称" prop="name">
                    <el-input placeholder="请输入货品名称" v-model="procform.name"></el-input>
                </el-form-item>
                <el-form-item label="单位" prop="unit">
                    <el-select placeholder="请选择单位" v-model="procform.unit" style="width: 200px;">
                        <el-option v-for="item in units" :key="item.dict_label" :label="item.dict_label" :value="item.dict_label"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="Reset">重置</el-button>
                    <el-button type="success" @click="Search">查询</el-button>
                </el-form-item>
            </el-form>
            <!--表格-->
            <el-table :data="procdata" stripe height="400" border @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column type="index" label="序号" width="70"></el-table-column>
                <el-table-column prop="proc_code" label="货品编号" width="200"></el-table-column>
                <el-table-column prop="proc_name" label="货品名称" width="150"></el-table-column>
                <el-table-column prop="proc_model" label="规格型号" width="120"></el-table-column>
                <el-table-column prop="proc_primary_unit" label="单位" width="80"></el-table-column>
                <el-table-column prop="type_name" label="货品类型" width="120"></el-table-column>
                <el-table-column prop="stk_hand_num" label="当前库存" width="100">
                    <template #default="scope">
                        {{ scope.row.stk_hand_num || 0 }}
                    </template>
                </el-table-column>
                <el-table-column prop="stk_price" label="单价" width="100">
                    <template #default="scope">
                        {{ scope.row.stk_price ? Number(scope.row.stk_price).toFixed(2) : '0.00' }}
                    </template>
                </el-table-column>
            </el-table>

            <div style="display: flex; justify-content: flex-end; margin-top: 15px;">
                 <!-- 页码 -->
                <el-pagination :page-size=10 :pager-count="11" layout="prev, pager, next,jumper" :total="rows"
                    v-on:current-change="handlePageChange">
                </el-pagination>
            </div>
        </div>
        <template #footer>
            <div style="text-align: right;">
                <el-button @click="dialogTableVisible = false">取消</el-button>
                <el-button type="success" @click="confirmProductSelection">确定</el-button>
            </div>
        </template>
    </el-dialog>
</template>
  
<script>
import {ref,reactive,onMounted} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox } from 'element-plus'; //提示信息
import { useRouter } from 'vue-router';//路由
import { ArrowDown } from '@element-plus/icons-vue';

export default {
    components: {
        ArrowDown
    },
    setup(){

        const router = useRouter();//路由
        //当前用户信息
        const user = JSON.parse(sessionStorage.getItem("user"));

         //规则验证
         const rules = reactive({
            start_time:[
                { required: true, message: '请选择盘点开始时间', trigger: 'blur' },
            ],
            whid:[
                { required: true, message: '请选择仓库', trigger: 'blur' },
            ],
            type:[
                { required: true, message: '请选择盘点类型', trigger: 'blur' },
            ],
            user:[
                { required: true, message: '请选择经办人', trigger: 'blur' },
            ]
        });

        //日期转换格式
        function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        //查询所有用户
        const users=ref([]);
        function GetAllUsers(){
            http.get("/User/GetAllUser")
            .then(res=>{
                users.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        // 当选择用户时，将用户名赋值给checkform.username
        function handleUserChange(userId) {
            const selectedUser = users.value.find(user => user.user_id === userId);
            if (selectedUser) {
                checkform.username = selectedUser.user_name;
            }
        }

        // 盘点类型
        const types = ref([]);
        function GetTypes() {
            return http.get("/BusinessType/GetBusinessTypes?field=盘点")
            .then(res => {
                types.value = res.data;
            }).catch(err => {
                console.log(err);
            })
        }

        //查询所有仓库
        const warehouse=ref([]);
        function GetAllWarehouse(){
            http.get("/Warehouse/GetWarehouses")
            .then(res => {
                warehouse.value = res.data;
                // 筛选出未锁定的仓库 (is_lock=0 表示未锁定)
                const availableWarehouses = res.data.filter(wh => wh.is_lock !== 1);
                const lockedWarehouses = res.data.filter(wh => wh.is_lock === 1);
                
                // 如果有锁定仓库，为它们添加特殊标记
                if (lockedWarehouses.length > 0) {
                    lockedWarehouses.forEach(wh => {
                        wh.wh_name = `${wh.wh_name} [已锁定]`;
                    });
                }
                
                // 合并可用仓库和锁定仓库，但锁定仓库将有明显标记
                warehouse.value = [...lockedWarehouses,...availableWarehouses];
            }).catch(err => {
                console.log(err);
            })
        }

        // 当选择仓库时，将仓库名称赋值给checkform.whname
        function warehouseChange(whId) {
            const selectedWarehouse = warehouse.value.find(wh => wh.wh_id === whId);
            console.log("选择的仓库:", selectedWarehouse);
            
            // 去掉 [已锁定] 标识，只保存原始仓库名称
            const originalWarehouseName = selectedWarehouse.wh_name.replace(' [已锁定]', '');
            checkform.whname = originalWarehouseName;
            
            // 如果选择的是未锁定的仓库，给出提示但不阻止选择
            if(selectedWarehouse.is_lock === 0){
                ElMessage.warning('该仓库未锁定，建议先锁定仓库后再进行盘点操作');
            }
        }

        //表单信息
        const checkref=ref("");
        const checkform=reactive({
            code:"",
            start_time: new Date(),
            end_time: "",
            type:"",
            whid:"",
            whname:"",
            user:"",
            username:"",
            remark:"",
        })

        
        //#region 上传附件
        const filelist = ref([])
        //头部带token
        const token=sessionStorage.getItem('token');
        const headers = {
             Authorization: `Bearer ${token}`, // 添加 token 到请求头
        };
        // 上传成功回调方法
        function handleFileSuccess(response, file, fileList) {
            if (Array.isArray(response)) {
                // 创建 { 文件名: URL } 的映射
                const urlMap = response.reduce((map, res) => {
                    if (res.success) map[res.originalName] = res.path;
                    return map;
                }, {});
                
                // 更新文件列表
                filelist.value = fileList.map(item => ({
                    ...item,
                    url: urlMap[item.name] || item.url,  // 优先使用新URL
                    status: urlMap[item.name] ? 'success' : item.status,
                    originalName: item.originalName || item.name
                }));
            }
        }

        function handleExceed() {
            ElMessage.warning('最多上传3个附件');
        }
        
        //预览
        function handlePreview(file){
            if (!file.url) {
                ElMessage.error('文件URL不存在，请重新上传');
                return;
            }
            const ext = file.name.split('.').pop().toLowerCase();
            
            switch (ext) {
                case 'jpg': case 'jpeg': case 'png': case 'gif': case 'bmp':
                    window.open(file.url, '_blank');
                    break;
                case 'pdf':
                    window.open(file.url, '_blank');
                    break;
                case 'doc': case 'docx': case 'xls': case 'xlsx': case 'ppt': case 'pptx':
                    window.open(file.url, '_blank');
                    break;
                default:
                    // 下载其他格式文件
                    const link = document.createElement('a');
                    link.href = file.url;
                    link.download = file.name;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
            }
        };

        //移除附件
        function handleRemove(file, fileList) {
            filelist.value = fileList;
        }
        //#endregion

        //#region 展示货品信息
        //查询所有单位
        const units=ref([]);
        function Getunit(){
            http.get("/DictData/GetAllDictDataBytype?typeid=8")
            .then(res=>{
                units.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }
        
        //模态框
        const dialogTableVisible=ref(false);
        function ShowProduct(){
            if (!checkform.whid) {
                ElMessage.warning('请先选择仓库');
                return;
            }
            
            // 再次检查仓库是否锁定
            const selectedWarehouse = warehouse.value.find(wh => wh.wh_id === checkform.whid);
            if (selectedWarehouse && selectedWarehouse.is_lock === 0) {
                ElMessage.warning('该仓库未锁定，请先锁定仓库后再进行盘点操作');
                return;
            }
            
            dialogTableVisible.value=true;
            Search(); // 选择仓库后直接加载货品
        }
        const procref=ref("");
        const procform=reactive({
            name:"",
            unit:"",
        })
        //表格数据
        const procdata = ref([]);
        //总数据量
        const rows = ref(0);
        //当前页
        const currentPage = ref(1);

        //重置
        function Reset(){
            procref.value?.resetFields();
            procform.name = "";
            procform.unit = "";
            Search(); // 重置后重新搜索
        }

         //查询
         async function Search() {
              try {
                  // 1. 获取指定仓库的库存数据
                  const stockRes = await http.get("/Stock/GetStockwhid", {
                      params: {
                          whid: checkform.whid,
                      }
                  });
                  
                  if (!stockRes.data || stockRes.data.length === 0) {
                      ElMessage({
                          message: '当前仓库没有货品.',
                          type: 'warning',
                      });
                      procdata.value = [];
                      return;
                  }
                  
                  // 2. 为每个库存项创建一个获取完整货品信息的Promise
                  const productPromises = stockRes.data.map(item =>
                      http.get(`/Product/GetProductById?id=${item.proc_id}`)
                  );
                  
                  // 3. 等待所有货品信息请求完成
                  const productResponses = await Promise.all(productPromises);
                  const products = productResponses.map(response => response.data);
                  
                  // 4. 将库存信息与完整的货品信息合并
                  procdata.value = stockRes.data.map(stockItem => {
                      const productInfo = products.find(p => p.proc_id === stockItem.proc_id);
                      return {
                          ...stockItem,                // 库存信息
                          ...(productInfo || {}),     // 完整的货品信息
                          // 确保使用库存中的正确字段
                          stock_num: stockItem.stk_hand_num || 0,
                          // 使用货品表中的参考入库价，而不是库存表的价格
                          price: productInfo?.instock_price || 0
                      };
                  });
              } catch (err) {
                  console.error("获取货品信息失败:", err);
                  ElMessage.error('获取库存货品失败');
                  procdata.value = [];
              }
          }

        // 页码改变
        function handlePageChange(val) {
            currentPage.value = val;
            Search();
        }

        // 选中的产品数组
        const selectedProducts = ref([]);
        // 当前选中的行
        const multipleSelection = ref([]);
        
        // 处理表格行选择变化
        function handleSelectionChange(selection) {
            multipleSelection.value = selection;
        }
        
        // 添加产品到已选清单
        function confirmProductSelection() {
            if(multipleSelection.value.length === 0) {
                ElMessage.warning('请至少选择一个产品');
                return;
            }
            
            // 为每个选中的产品添加必要的字段
            multipleSelection.value.forEach(item => {
                // 检查是否已经添加过该产品
                const existingIndex = selectedProducts.value.findIndex(p => p.proc_id === item.proc_id);
                
                if(existingIndex === -1) {
                    // 添加新产品
                    const newItem = {
                        ...item,
                        // 使用库存表中的字段
                        check_num: item.stk_hand_num || 0, // 默认实盘数量等于账面数量
                        profit_loss_num: 0,
                        profit_loss_amount: 0,
                        check_status: '无盈亏',
                        price: item.instock_price || 0,
                        remark: ''
                    };
                    selectedProducts.value.push(newItem);
                } else {
                    // 已存在则不做任何处理
                    ElMessage.info(`货品"${item.proc_name}"已在盘点清单中`);
                }
            });
            
            dialogTableVisible.value = false;
        }
        
        // 计算盈亏数量和金额
        function calculateDifference(row) {
            const stockNum = row.stk_hand_num || 0;
            const checkNum = row.check_num || 0;
            const price = row.price || 0;
            
            // 盈亏数量 = 实盘数量 - 账面数量
            row.profit_loss_num = checkNum - stockNum;
            
            // 盈亏金额 = 盈亏数量 * 单价
            row.profit_loss_amount = row.profit_loss_num * price;
            
            // 设置盘点状态
            if (row.profit_loss_num > 0) {
                row.check_status = '盘盈';
            } else if (row.profit_loss_num < 0) {
                row.check_status = '盘亏';
            } else {
                row.check_status = '无盈亏';
            }
        }
        
        // 计算实盘总数量
        function calculateTotalQuantity() {
            if (selectedProducts.value.length === 0) return 0;
            return selectedProducts.value.reduce((total, product) => {
                return total + (product.check_num || 0);
            }, 0);
        }
        
        // 计算盘盈数量
        function calculateProfitQuantity() {
            if (selectedProducts.value.length === 0) return 0;
            return selectedProducts.value.reduce((total, product) => {
                const diff = (product.profit_loss_num || 0);
                return total + (diff > 0 ? diff : 0);
            }, 0);
        }
        
        // 计算盘亏数量
        function calculateLossQuantity() {
            if (selectedProducts.value.length === 0) return 0;
            return Math.abs(selectedProducts.value.reduce((total, product) => {
                const diff = (product.profit_loss_num || 0);
                return total + (diff < 0 ? diff : 0);
            }, 0));
        }
        
        // 计算盘盈金额
        function calculateProfitAmount() {
            if (selectedProducts.value.length === 0) return '0.00';
            const total = selectedProducts.value.reduce((sum, product) => {
                const amount = (product.profit_loss_amount || 0);
                return sum + (amount > 0 ? amount : 0);
            }, 0);
            return total.toFixed(2);
        }
        
        // 计算盘亏金额
        function calculateLossAmount() {
            if (selectedProducts.value.length === 0) return '0.00';
            const total = Math.abs(selectedProducts.value.reduce((sum, product) => {
                const amount = (product.profit_loss_amount || 0);
                return sum + (amount < 0 ? amount : 0);
            }, 0));
            return total.toFixed(2);
        }

        // 计算账面库存总数
        function calculateBookInventory() {
            if (selectedProducts.value.length === 0) return 0;
            return selectedProducts.value.reduce((total, product) => {
                return total + (product.stk_hand_num || 0);
            }, 0);
        }
        
        // 计算账面金额总额
        function calculateBookAmount() {
            if (selectedProducts.value.length === 0) return '0.00';
            const total = selectedProducts.value.reduce((sum, product) => {
                return sum + (product.stk_total || 0);
            }, 0);
            return total.toFixed(2);
        }

        // 移除产品
        function removeProduct(procId) {
            // 通过产品ID查找对应的索引位置
            const index = selectedProducts.value.findIndex(item => item.proc_id === procId);
            if (index !== -1) {
                // 找到对应产品后从数组中删除
                selectedProducts.value.splice(index, 1);
            }
        }


        const selectdata=ref([]);//选中数据
        //获取选中数据
        function SelectChange(val){
            selectdata.value=val;
        }
        //批量移除
        function batchRemoveProducts(){
            if(selectdata.value.length===0){
                ElMessage.warning('请先选择要移除的货品');
                return;
            }
            selectdata.value.forEach(item=>{
                const index=selectedProducts.value.findIndex(p=>p.proc_id===item.proc_id);
                if(index!==-1){
                    selectedProducts.value.splice(index,1);
                }
            });
            ElMessage.success('已移除'+selectdata.value.length+'个货品');
        }
        //#endregion


        //#region 添加
        async function Add(status = 2) { 
            try {
                //1.验证表单
                const [checkValid] = await Promise.all([
                    new Promise(resolve => checkref.value.validate(resolve)),
                ]);
                if (!checkValid) {
                    return false;
                }

                //2.验证必须有货品信息
                if(selectedProducts.value.length === 0) {
                    ElMessage.error('请至少添加一个货品到盘点明细');
                    return false;
                }
                
                //3.再次检查仓库是否锁定（防止在操作过程中被解锁）
                const selectedWarehouse = warehouse.value.find(wh => wh.wh_id === checkform.whid);
                if (selectedWarehouse && selectedWarehouse.is_lock === 0) {
                    ElMessage.error('该仓库未锁定，请先锁定仓库后再进行盘点操作');
                    return false;
                }

                //4.生成编号
                const codeRes = await http.get("/CodeRule/GeneratedCode?id=25"); // 修改为盘点单编号规则ID

                // 计算盘盈盘亏数据
                const checkprofitNum = calculateProfitQuantity();
                const checklossesNum = calculateLossQuantity();
                
                // 根据盘盈盘亏情况自动设置状态
                // 如果有盘盈或盘亏，状态设为2（有盈亏），否则设为3（无盈亏）
                const autoStatus = (checkprofitNum > 0 || checklossesNum > 0) ? 2 : 3;
                
                //5.准备添加数据
                //盘点单
                const checkdata = {
                    ic_code: codeRes.data,
                    ic_type: checkform.type,
                    start_time: formatDateTime(checkform.start_time),
                    end_time: checkform.end_time ? formatDateTime(checkform.end_time) : null,
                    wh_id: checkform.whid,
                    wh_name: checkform.whname,
                    ic_user: checkform.username,
                    ic_status: status === 1 ? 1 : autoStatus, // 如果是草稿则保持1，否则根据盈亏情况自动设置
                    instock_status: 4,
                    outstock_status: 7,
                    bookinventory: calculateBookInventory(),
                    bookamount: calculateBookAmount(),
                    check_num: calculateTotalQuantity(),
                    checkprofit_num: checkprofitNum,
                    checklosses_num: checklossesNum,
                    checkprofit_total: calculateProfitAmount(),
                    checklosses_total: calculateLossAmount(),
                    create_name: user.name,
                    create_time: formatDateTime(new Date()),
                    remark: checkform.remark,
                };

                //盘点明细单数据
                const checkdetaildata = selectedProducts.value.map(item => {
                    return {
                        ic_id: 0,
                        proc_id: item.proc_id,
                        proc_name: item.proc_name,
                        icd_num:item.check_num,
                        profitandloss_num:item.profit_loss_num,
                        icd_status:item.check_status,
                        icd_price:item.price,
                        profitandloss_total:item.profit_loss_amount,
                        instock_status:4,
                        outstock_status:7,
                        remark:item.remark,
                    }
                });

                //附件
                const filelistdata = filelist.value.map(item => {
                    return {
                        business_type:"盘点单",
                        business_code:checkform.code,
                        title: item.originalName,
                        file_name: item.url,
                    }
                })

                 // 将所有数据整合到一个 payload 对象中，用于事务性提交
                let payload = {
                    checkData: checkdata,
                    checkDetails: checkdetaildata,
                    attachments: filelistdata
                };

                console.log("发往后端的完整数据包 (Payload):", payload);
                const res = await http.post("/Check_h/AddCheck_h", payload);
                if (res.data > 0) {
                    ElMessage.success("添加成功");
                    return true;
                } else {
                    ElMessage.error("添加失败");
                    return false;
                }
            } catch (err) {
                console.log(err);
                ElMessage.error('操作失败');
                return false;
            }
        } 
        //#endregion

        //保存为草稿
        async function SaveAsDraft() {
            const result = await Add(1); // 传入状态 1 表示草稿
            if (result) {
                router.push("check");
            }
        }
        
        //保存
        async function OK() {
            const result = await Add(2); // 传入状态 2 表示待审核
            if (result) {
                router.push("check");
            }
        }

        //保存并新增
        async function OKAdd(){
            const result = await Add(2); // 传入状态 2 表示待审核
            if(result){
                //清空
                checkref.value.resetFields();
                selectedProducts.value = [];
                filelist.value = [];
            }
        }

        //关闭
        function Close(){
            router.back();
        }

        //跳转仓库页面
        function SetWarehouse(){
            router.push("warehouse");
        }

        //挂载
        onMounted(() => {
           Getunit();
           GetTypes();
           GetAllWarehouse();
           GetAllUsers();
        });

        return{
            rules,
            Add,
            OK,
            OKAdd,
            Close,
            handleFileSuccess,
            handlePreview,
            handleExceed,
            headers,
            filelist,
            ShowProduct,
            dialogTableVisible,
            procref,
            procform,
            procdata,
            rows,
            currentPage,
            Reset,
            units,
            Search,
            handlePageChange,
            confirmProductSelection,
            checkform,
            checkref,
            warehouse,
            warehouseChange,
            users,
            handleUserChange,
            selectedProducts,
            handleSelectionChange,
            removeProduct,
            calculateDifference,
            calculateTotalQuantity,
            calculateProfitQuantity,
            calculateLossQuantity,
            calculateProfitAmount,
            calculateLossAmount,
            SaveAsDraft,
            SelectChange,
            batchRemoveProducts,
            selectdata,
            handleRemove,
            types,
            SetWarehouse
        }
    }
}
</script>
  
<style scoped>
    /* 白色圆角容器 - 核心样式 */
    .white-container {
        background: white;
        border-radius: 12px;
        margin-bottom: 50px;
        box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
        width: 75%;
    }

    /* 底部操作栏自适应 */
    .action-bar {
        position: fixed;
        bottom: 0;
        right: 0.5%; /* 与表单右侧对齐 */
        left: 210px; /* 与菜单栏宽度一致 */
        background: white;
        border-top: 1px solid #e6e6e6;
        padding: 15px;
        text-align: right;
    }

    /* 模态框样式 */
    :deep(.el-dialog__body) {
        padding: 10px 20px;
    }
    
    :deep(.el-dialog__footer) {
        border-top: 1px solid #e6e6e6;
        padding: 10px 0;
    }
    
    :deep(.el-dialog__header) {
        border-bottom: 1px solid #e6e6e6;
    }
</style>

